/*******************************************************************************
 * Copyright (c) 2006 Ultimate Technology, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Bojan Vukojevic - initial API and implementation
 *******************************************************************************/
package com.ultimatetech.cim.views;

import javax.wbem.cim.CIMInstance;
import javax.wbem.cim.CIMObjectPath;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.part.*;

import org.eclipse.core.runtime.Preferences;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.*;

import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.jface.action.*;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.*;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.SWT;

import com.ultimatetech.cim.CIMPlugin;
import com.ultimatetech.cim.preferences.CIMPreferencePage;
import com.ultimatetech.cim.views.content.ClassInstances;
import com.ultimatetech.cim.views.content.ClassNames;


/**
 * This sample class demonstrates how to plug-in a new
 * workbench view. The view shows data obtained from the
 * model. The sample creates a dummy model on the fly,
 * but a real implementation would connect to the model
 * available either in this or another plug-in (e.g. the workspace).
 * The view is connected to the model using a content provider.
 * <p>
 * The view uses a label provider to define how model
 * objects should be presented in the view. Each
 * view can present the same model objects using
 * different labels and icons, if needed. Alternatively,
 * a single label provider can be shared between views
 * in order to ensure that objects of the same type are
 * presented in the same way everywhere.
 * <p>
 */

public class Enumerate extends ViewPart {
	
	private static String COLUMN_NAMES[] = new String[] {
		"Host", "Namespace", "Class Name"
	};
	private TableViewer viewer;
	private TableViewer instanceViewer;
	private Action action1;
	private Action action2;
	private Action doubleClickAction;
	IPropertyChangeListener propChangeListener;
	
	class CIMProps {
		String host;
		String namespace;
		String port;
		String protocol;
	}
	//private Table table;

	/*
	 * The content provider class is responsible for
	 * providing objects to the view. It can wrap
	 * existing objects in adapters or simply return
	 * objects as-is. These objects may be sensitive
	 * to the current input of the view, or ignore
	 * it and always show the same content 
	 * (like Task List, for example).
	 */
	 
	class ViewContentProvider implements IStructuredContentProvider {
		public void inputChanged(Viewer v, Object oldInput, Object newInput) {
			System.out.println("Input changed");
		}
		public void dispose() {
		}
		public Object[] getElements(Object parent) {
			try {
				Preferences pref = CIMPlugin.getDefault().getPluginPreferences();				
			ClassNames cn = new ClassNames(pref);
			return cn.getClassNames().toArray();
			} catch (Throwable t){
				t.printStackTrace();
			}
			
			return new String[] { "Error", "No data", "" };
		}
	}
	class ViewLabelProvider extends LabelProvider implements ITableLabelProvider {
		public String getColumnText(Object obj, int index) {
			String result = "";
			CIMObjectPath cop = (CIMObjectPath) obj;
			
			switch (index) {
				case 0: 
					result = cop.getHost();
					break;
				case 1 :
					result = cop.getNameSpace();
					break;
				case 2 :
					result = cop.getObjectName();
					break;				
				default :
					break; 	
			}
			return result;		
		}
			
		public Image getColumnImage(Object obj, int index) {
			return null;
			//return getImage(obj);
		}/*
		public Image getImage(Object obj) {
			return PlatformUI.getWorkbench().
					getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
		}*/
	}
	class ClassInstanceContentProvider implements IStructuredContentProvider {
		CIMObjectPath c = null;
		ClassInstanceContentProvider(CIMObjectPath cop){
			c = cop;
		}
		public void inputChanged(Viewer v, Object oldInput, Object newInput) {
		}
		public void dispose() {
			c = null;
		}
		public Object[] getElements(Object parent) {
			if(c != null){
				Preferences pref = CIMPlugin.getDefault().getPluginPreferences();
				ClassInstances ci = new ClassInstances(c, pref, false);
				return ci.getInstances().toArray();
			}
			return new String[]{"......"};
			/*ClassNames cn = new ClassNames();
			return cn.getClassNames().toArray();*/
			//return new String[] {"Select a class from the top table"};
			//return new String[] { "One", "Two", "Three" };
		}
	}
	class ClassInstanceLabelProvider extends LabelProvider implements ITableLabelProvider {
		public String getColumnText(Object obj, int index) {
			String result = "";
			CIMInstance ci = (CIMInstance) obj;
			
			switch (index) {
				case 0: 
					result = ci.toMOF();
					break;
				/*case 1 :
					result = cop.getNameSpace();
					break;
				case 2 :
					result = cop.getObjectName();
					break;				*/
				default :
					break; 	
			}
			return result;		
		}
			
		public Image getColumnImage(Object obj, int index) {
			return null;
			//return getImage(obj);
		}/*
		public Image getImage(Object obj) {
			return PlatformUI.getWorkbench().
					getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
		}*/
	}
	class NameSorter extends ViewerSorter {
	}
	
	
	class CIMPropChangeListener implements IPropertyChangeListener {

		public void propertyChange(org.eclipse.jface.util.PropertyChangeEvent event) {
			boolean cimPropchanged = false;
			if (event.getProperty().equals(CIMPreferencePage.PreferenceNames.CIM_HOST)) {
				cimPropchanged = true;
			} else if(event.getProperty().equals(CIMPreferencePage.PreferenceNames.CIM_NAMESPACE)){
				cimPropchanged = true;
			} else if(event.getProperty().equals(CIMPreferencePage.PreferenceNames.CIM_PORT)){
				cimPropchanged = true;
			}else if(event.getProperty().equals(CIMPreferencePage.PreferenceNames.CIM_FILTER)){
				cimPropchanged = true;
			}
			if(cimPropchanged){				
				viewer.getTable().removeAll();
				instanceViewer.getTable().removeAll();				
				viewer.setContentProvider(new ViewContentProvider());
				viewer.setLabelProvider(new ViewLabelProvider());
				viewer.setSorter(new NameSorter());
				viewer.setInput(getViewSite());
				instanceViewer.getTable().getColumn(0).setText("Double click on the class to see instances...");
				
			}
		}
 	}

	/**
	 * The constructor.
	 */
	public Enumerate() {
	}

	/**
	 * This is a callback that will allow us
	 * to create the viewer and initialize it.
	 */
	public void createPartControl(Composite parent) {		
		viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);			
		Table t = viewer.getTable();
		GridData gridData = new GridData(GridData.FILL_BOTH);
		gridData.grabExcessVerticalSpace = true;
		gridData.horizontalSpan = 3;
		t.setLayoutData(gridData);						
		t.setLinesVisible(true);
		t.setHeaderVisible(true);
		addTableColumns(viewer.getTable());
		viewer.setColumnProperties(COLUMN_NAMES);
		
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setSorter(new NameSorter());
		viewer.setInput(getViewSite());
		
		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
		
		instanceViewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);	
		Table it = instanceViewer.getTable();
		gridData = new GridData(GridData.FILL_BOTH);
		gridData.grabExcessVerticalSpace = true;
		gridData.horizontalSpan = 3;
		it.setLayoutData(gridData);						
		it.setLinesVisible(true);
		it.setHeaderVisible(true);
		
		instanceViewer.setColumnProperties(new String[] {"Select class to view instances..."});
		TableColumn column = new TableColumn(instanceViewer.getTable(), SWT.LEFT, 0);
		column.setWidth(300);
		column.setText("Select class to view instances...");
		propChangeListener = new CIMPropChangeListener();
		CIMPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(propChangeListener);
		/*instanceViewer.setContentProvider(new ClassInstanceContentProvider(null));
		instanceViewer.setLabelProvider(new ClassInstanceLabelProvider());*/
		//instanceViewer.setSorter(new NameSorter());
		
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				Enumerate.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(action1);
		manager.add(new Separator());
		manager.add(action2);
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(action1);
		manager.add(action2);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}
	
	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(action1);
		manager.add(action2);
	}

	private void makeActions() {
		action1 = new Action() {
			public void run() {
				showMessage("Action 1 executed");
			}
		};
		action1.setText("Action 1");
		action1.setToolTipText("Action 1 tooltip");
		action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
			getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		
		action2 = new Action() {
			public void run() {
				showMessage("Action 2 executed");
			}
		};
		action2.setText("Action 2");
		action2.setToolTipText("Action 2 tooltip");
		action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
				getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		doubleClickAction = new Action() {
			public void run() {
					instanceViewer.getTable().setHeaderVisible(true);					
					instanceViewer.getTable().setEnabled(false);
					instanceViewer.setColumnProperties(new String[] {"Retrieving data..."});
					instanceViewer.getTable().removeAll();
					instanceViewer.getTable().redraw();					
					instanceViewer.insert("Retrieving data....", 0);
					instanceViewer.setContentProvider(new ClassInstanceContentProvider(null));	
					instanceViewer.setInput(getViewSite());
					instanceViewer.refresh();
				
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection)selection).getFirstElement();
				CIMObjectPath cop = (CIMObjectPath) obj;
				//instanceViewer.setColumnProperties(new String[] {"Instance"});
				instanceViewer.setContentProvider(new ClassInstanceContentProvider(cop));	
				instanceViewer.setInput(getViewSite());
				instanceViewer.getTable().setLinesVisible(true);
				instanceViewer.getTable().setEnabled(true);
				//instanceViewer.setColumnProperties(new String[] {"Number of instances:" + instanceViewer.getTable().getItemCount()});
				//TableColumn column = new TableColumn(instanceViewer.getTable(), SWT.LEFT, 0);
				instanceViewer.getTable().getColumn(0).setText("Number of instances:" + instanceViewer.getTable().getItemCount());
				//column.setText("Number of instances:" + instanceViewer.getTable().getItemCount());
				//column.setWidth(300);
				instanceViewer.refresh();
				//instanceViewer.add(cop);
				//showMessage("Double-click detected on "+obj.toString());
			}
		};
	}
	
	
	private void addTableColumns(Table objectPathTable){
		TableColumn column = new TableColumn(objectPathTable, SWT.LEFT, 0);		
		column.setText(COLUMN_NAMES[0]);
		column.setWidth(100);
		column = new TableColumn(objectPathTable, SWT.LEFT, 1);
		column.setText(COLUMN_NAMES[1]);
		column.setWidth(100);
		column = new TableColumn(objectPathTable, SWT.LEFT, 2);
		column.setText(COLUMN_NAMES[2]);
		column.setWidth(400);				
	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}
	private void showMessage(String message) {
		MessageDialog.openInformation(
			viewer.getControl().getShell(),
			"Enumerate Classes",
			message);
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		if(viewer != null){
		viewer.getControl().setFocus();
		} else {
			System.out.println("Viewer is null...");
		}
	}

	public void dispose() {
		CIMPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(propChangeListener);
		super.dispose();
	}
}